<?php
/**
 * Note: 接口异常处理, 返回自定义校验码
 */
namespace App\Exceptions;

use Throwable;

class ApiHttpOkException extends \Exception
{
    /**
     * 响应给客户端的附加数据
     * @var mixed|null
     */
    private $data;

    public const CODE_AUTH_FAILED = 401;

    // 账户相关
    public const CODE_AUTH_CHECK_FAILED = 1000;
    public const CODE_NO_REGISTER = 1001;
    public const CODE_MOBILE_ALREADY_USE = 1002;
    public const CODE_PASSWORD_NOT_MATCH = 1003;
    public const CODE_RELATION_NOT_MATCH = 1004;
    public const CODE_NO_LOGIN = 1005;
    public const CODE_WECHAT_ALREADY_BIND = 1006;
    public const CODE_UUID_ALREADY_BIND = 1007;
    public const CODE_SOURCE_NOT_MATCH = 1008;

    // CPL相关
    public const CODE_ISSUE_NOT_FOUND = 2000;
    public const CODE_ISSUE_USER_NOT_ACTIVE = 2001;
    public const CODE_ISSUE_IS_EXPIRED = 2002;

    // 预设的异常码
    public const EXCEPTIONS = [
        self::CODE_AUTH_FAILED => 'auth.failed',

        self::CODE_AUTH_CHECK_FAILED => 'auth.failed',
        self::CODE_NO_REGISTER => 'auth.no_register',
        self::CODE_MOBILE_ALREADY_USE => 'auth.mobile_already_use',
        self::CODE_PASSWORD_NOT_MATCH => 'auth.password_not_match',
        self::CODE_RELATION_NOT_MATCH => 'auth.relation_not_match',
        self::CODE_NO_LOGIN => 'auth.no_login',
        self::CODE_WECHAT_ALREADY_BIND => 'auth.wechat_already_bind',
        self::CODE_UUID_ALREADY_BIND => 'auth.uuid_already_bind',
        self::CODE_SOURCE_NOT_MATCH => 'auth.source_not_match',

        self::CODE_ISSUE_NOT_FOUND => 'api.issue_not_found',
        self::CODE_ISSUE_USER_NOT_ACTIVE => 'api.issue_user_not_active',
        self::CODE_ISSUE_IS_EXPIRED => 'api.issue_is_expired',
    ];

    /**
     * ApiException constructor.
     * @param string $message
     * @param null $data
     * @param int $code
     * @param Throwable|null $previous
     */
    public function __construct($message = '', $data = null, $code = 422, \Throwable $previous = null)
    {
        $this->data = $data;
        if (is_numeric($message) && isset(self::EXCEPTIONS[$message])) {
            $code = $message;
            $message = __(self::EXCEPTIONS[$message]);
        }
        parent::__construct($message, $code, $previous);
    }

    /**
     * @return mixed|null
     */
    public function getData()
    {
        return $this->data;
    }
}
